package es.hekorusoft.udpcache.messages;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;

/*
 This file is part of UDPCache.

 UDPCache is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 UDPCache is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with UDPCache.  If not, see <http://www.gnu.org/licenses/>.
 */
final class StreamWriter {

	public static final void addByte(int value, OutputStream baos) throws IOException {
		baos.write(value);
	}

	public static final void addInt(int number, OutputStream baos) throws IOException {

		byte[] b = new byte[4];
		b[0] = (byte) (0xFF & number >> 24);
		b[1] = (byte) (0xFF & number >> 16);
		b[2] = (byte) (0xFF & number >> 8);
		b[3] = (byte) (0xFF & number);
		baos.write(b);
	}

	public static final void addLong(long number, OutputStream baos) throws IOException {

		byte[] b = new byte[8];
		b[7] = (byte) (number);
		number >>>= 8;
		b[6] = (byte) (number);
		number >>>= 8;
		b[5] = (byte) (number);
		number >>>= 8;
		b[4] = (byte) (number);
		number >>>= 8;
		b[3] = (byte) (number);
		number >>>= 8;
		b[2] = (byte) (number);
		number >>>= 8;
		b[1] = (byte) (number);
		number >>>= 8;
		b[0] = (byte) (number);

		baos.write(b);

	}

	public static final void addString(String str, OutputStream baos) throws IOException {

		byte[] strArray = str.getBytes();
		addInt(strArray.length, baos);
		baos.write(strArray);

	}

	public static final void addObject(Object obj, OutputStream baos) throws IOException {

		final byte[] data;

		ByteArrayOutputStream ba = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(ba);
		oos.writeObject(obj);
		oos.close();

		if (ba.size() > 60000) {
			System.out.println("Extra compression!");
			ByteArrayOutputStream gba = new ByteArrayOutputStream();
			GZIPOutputStream gos = new GZIPOutputStream(gba);
			gos.write(ba.toByteArray());
			gos.close();
			data = gba.toByteArray();
		} else {
			data = ba.toByteArray();
		}
		addInt(data.length, baos);
		baos.write(data);

	}

	public static final void addByteArray(byte[] array, OutputStream baos) throws IOException {
		addInt(array.length, baos);
		baos.write(array);
	}

}
